import axios from "axios"
import router from "@/router";
import { MessageBox, Message, Loading } from 'element-ui';
import qs from "qs"
import store from "@/store";
import jsCookie from 'js-cookie'
export let isRelogin = { show: false };
/**
 * 处理错误信息
 * @param {*} status  状态码
 * @param {*} info    具体信息
 */
const errorHandle = (status, info) => {
  switch (status) {
    case 400:
      Message({
        message: '语义有误',
        type: 'error',
        duration: 5 * 1000
      });
      break;
    case 401:
      Message({
        message: '服务器认证失败',
        type: 'error',
        duration: 5 * 1000
      });
      break;
    case 404:
      Message({
        message: '地址错误',
        type: 'error',
        duration: 5 * 1000
      });
      break;
    case 500:
      Message({
        message: '服务器繁忙',
        type: 'error',
        duration: 5 * 1000
      });
      break;
    case 2003:
      Message({
        message: '接口调用失败',
        type: 'error',
        duration: 5 * 1000
      });
      break;
    case 403:
      Message({
        message: '没有权限访问资源',
        type: 'error',
        duration: 5 * 1000
      });
      break;
    case 2005:
      Message({
        message: 'Token过期',
        type: 'error',
        duration: 5 * 1000
      });
      break;
    default:
      console.log(info);
      break;
  }
}


const instance = axios.create({
  timeout: 5000
})

//请求拦截
instance.interceptors.request.use(
  config => {
    var token = jsCookie.get("token")
    if (token != null) {
      config.headers['Authorization'] = token
    }
    return config;
  },
  error => Promise.reject(error)
)

//响应链接
instance.interceptors.response.use(
  response => {
    if (response.config.responseType === 'blob') {  // 下载时直接return 返回blob
      loadingInstance && loadingInstance.close();
      return response.data;
    }
    const res = response.data;

    if (res.code == 2005 || res.code == 2006) {
      // 判断当前页面的位置
      if (!isRelogin.show) {
        isRelogin.show = true;
        MessageBox.confirm('很抱歉，登录已过期，请重新登录', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          isRelogin.show = false;
          jsCookie.remove('username')
          jsCookie.remove('token')
          router.push({ path: '/login' });
        }).catch(() =>{
          isRelogin.show = false;
        })
      }
    }
    if (response.data.code !== 2001) {
      // 失败
      return Promise.reject(response);
    } else {
      // 成功
      return Promise.resolve(response);
    }
  },
  error => {
    if (!error.request.response) {
      Message({
        message: '服务连接失败',
        type: 'error',
        duration: 5 * 1000
      });
      return Promise.reject(error);
    }
  }

)

export default instance;